<template>
  <j-modal
    :title="name + '权限对象'"
    width='80%'
    :bodyStyle="{ minWidth: '800px',overFlow:'scroll' }"
    :visible='display'
    switchFullscreen
    @cancel='close'
    cancelText='关闭'>
    <template slot='footer'>
      <a-button @click='close'>取消</a-button>
      <a-button type='primary' @click='handleOk'>确认</a-button>
    </template>
    <!-- 查询区域 -->
    <!--    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />-->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button type='primary' @click='handleAddStore'>新增</a-button>
      <!--      <a-button type='primary' @click='batchDel'>删除</a-button>-->

      <!--      <a-button type='primary' @click='handleClose' v-has="'feeApply:close'">核销关闭</a-button>-->
      <!--      <a-button type='primary' @click='handleRedeal' v-has="'feeApply:passs'">审批通过</a-button>-->
      <!--      <a-button type='primary' v-has="'feeApply:special'" @click='handleAddStore'  :disabled='selectedRowKeys.length !== 1'>-->
      <!--        核销特批-->
      <!--        &lt;!&ndash;        handleSpecial&ndash;&gt;-->
      <!--      </a-button>-->
      <!--      <a-button type='primary' icon='download' v-has="'feeApply:getOut'" @click="downExportXls('tpmAudit_service')">导出-->
      <!--      </a-button>-->
    </div>
    <!-- table区域-begin -->
    <a-table
      ref='table'
      size='middle'
      bordered
      rowKey='id'
      :scroll='{x:1500,y:pageHeight-seachHeight-220}'
      :columns='columns'
      :dataSource='dataSource'
      :pagination='ipagination'
      class=''
      :loading='loading'
      :customRow='onClickRow'
      :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:"checkbox"}'
      @change='handleTableChange'>
      <template slot='actName' slot-scope='t,r,dex'>
        <a @click='handleEdit(r,"detail")'>{{ t }}</a>
      </template>
      <span slot='action' slot-scope='text, record'>
           <a-popconfirm title='确定删除吗?' @confirm="() => handleDelete(record.id)">
              <a>删除</a>
           </a-popconfirm>
        </span>
    </a-table>

    <form-add-edit ref='popupForm' @ok='modelFormOkss'></form-add-edit>
  </j-modal>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import search from '@comp/view/base-crud/search/Search'
import HpayselectCom from '@/components/cn-components/HpayselectCom'
import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'

export default {
  description: '菜单管理-权限对象页面',
  name: 'permissObject',
  mixins: [PageListMixin],
  components: {
    search,
    HpayselectCom,
    FormAddEdit
  },
  data() {
    return {
      name:'',
      modal: {},
      display: false,
      loading: false,
      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'permflag',
          placeholder: '请输入接口字符'
        }
        // {
        //   // label:'业务员',
        //   type: 'input',
        //   name: 'actName',
        //   placeholder: '请输入权限名称'
        // },

      ],
      // 表头
      columns: [
        {
          title: '菜单编号',
          align: 'left',
          dataIndex: 'functionCode'
        },
        {
          title: '权限对象',
          align: 'left',
          dataIndex: 'dataTypeName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      url: {
        lists: window._CONFIG['domianURL'] + '/sysFunPermsObjController/getFunPermByFunCode',
        delete: window._CONFIG['domianURL'] + '/sysFunPermsObjController/delete',

        detail: window._CONFIG['domianTpmURL'] + '/tpmAudit/getAuditDetail',
        closeOne: window._CONFIG['domianTpmURL'] + '/tpmAudit/closeAudit',
        stopOne: window._CONFIG['domianTpmURL'] + '/tpmAudit/takeBackAudit',
        checks: window._CONFIG['domianTpmURL'] + '/tpmAudit/commitAudit',
        deals: window._CONFIG['domianTpmURL'] + '/tpmAudit/approvedToAccount',
        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        deleteBatch: window._CONFIG['domianTpmURL'] + '/activity/delete'
      }
    }
  },
  methods: {
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      getAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadDatass();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    edit(record) {
      console.log(record)
      this.name = record.name
      this.display = true
      this.modal = Object.assign({}, record)
      this.isorter.funCode = record.functionCode
      this.loadDatass()
    },
    loadDatass() {
      let params = this.getQueryParams()//查询条件
      getAction(this.url.lists, params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.dataSource = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getQueryParams() {
      var param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize

      return param
    },
    modelFormOkss(val) {
      console.log(val)
      let params = {
        functionCode: this.modal.functionCode,
        ...val
      }
      let url = window._CONFIG['domianURL'] + '/sysFunPermsObjController/saveOrUpdateEntity'
      postAction(url, { ...params }).then(res => {
        if (res.success) {
          this.$message.info(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.$refs.popupForm.confirmLoading = false
        this.$refs.popupForm.close()
        this.loadDatass()
      })
    },
    handleAddStore() {
      let config = {
        title: '新增权限对象',
        width: 500,
        list: [
          {
            label: '权限对象',
            type: 'j-select',
            dictCode: 'perms_type',
            placeholder: '请选择权限对象',
            name: 'dataType',  // 后台接受字段
            check: { rules: [{ required: true, message: '请选择权限对象' }] }
          }
        ]
      }
      this.$refs.popupForm.edit({}, config)
      this.$refs.popupForm.disableSubmit = false
    },
    handleSpecial() {
      let url = window._CONFIG['domianTpmURL'] + '/tpmAudit/commitAuditExamined'
      getAction(url, { id: this.selectedRowKeys[0] }).then(res => {
        res.success ? this.$message.info(res.message) : this.$message.error(res.message)
      })
    },
    handleRedeal() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.info('请至少选择一项')
        return
      }
      let ids = ' '
      let that = this
      ids = this.selectedRowKeys.join(',').toString()
      getAction(that.url.deals, { ids: ids }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadDatass()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    addToStop(record, status) {
      let url = ''
      if (status == 'stopOne') {
        url = this.url.stopOne
      } else if (status == 'checks') {
        url = this.url.checks
      }
      let that = this
      getAction(url, { id: record.id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadDatass()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    handleClose: function() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        let rows = this.selectionRows
        let ids = this.selectionRows[this.selectedRowKeys.length - 1].id
        var that = this
        this.$confirm({
          title: '确认关闭',
          content: `是否关闭 [ ${this.selectionRows[this.selectedRowKeys.length - 1].actName} ] ?`,
          onOk: function() {
            that.loading = true
            getAction(that.url.closeOne, { id: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadDatass()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    handleEdit: async function(record, status) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id })
        if (res.success) {
          record = res.result
        } else {
          this.$message.error(res.message)
        }
      }
      if (status == 'detail') {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '详情'
        this.$refs.modalForm.disableSubmit = true
        this.$refs.modalForm.unOrDown = false
        this.$refs.modalForm.unDownUrl = false
        this.$refs.modalForm.unOrDowntitle = '点击下载'
      } else {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
        this.$refs.modalForm.unOrDown = true
        this.$refs.modalForm.unDownUrl = true
        this.$refs.modalForm.unOrDowntitle = '点击上传'
      }
    },
    close() {
      this.display = false
    },
    handleOk() {
      this.close()
      this.$emit('ok')
    }

  },
  created() {

  },


  // beforeMount() {
  //   const draggingMap = {};
  //   this.columns.forEach((col) => {
  //     draggingMap[col.dataIndex] = col.width;
  //   });
  //   const draggingState = Vue.observable(draggingMap);
  //   const resizeableTitle = (h, props, children) => {
  //     let thDom = null;
  //     const { key, ...restProps } = props;
  //     console.log(props)
  //     let col;
  //     // 复选框筛选处理
  //     if (key === 'selection-column') {
  //       col = {};
  //     } else {
  //       col = this.columns.find((item) => {
  //         const k = item.dataIndex || item.key;
  //         return k === key;
  //       });
  //     }
  //     // 未设置宽度或者设置不可伸缩时不做伸缩处理
  //     if (!col.width || col.noStretch) {
  //       return <th {...restProps}>{children}</th>;
  //     }
  //     const onDrag = (x) => {
  //       draggingState[key] = 0;
  //       // 设置一个伸缩的最小宽度，防止页面错乱
  //       col.width = Math.max(x, col.minWidth || 30);
  //     };
  //     const onDragstop = () => {
  //       draggingState[key] = thDom.getBoundingClientRect().width;
  //     };
  //     return (
  //       <th
  //         {...restProps}
  //         v-ant-ref={(r) => (thDom = r)}
  //         width={col.width}
  //         class="resize-table-th"
  //       >
  //         {children}
  //         <vue-draggable-resizable
  //           key={col.key}
  //           class="table-draggable-handle"
  //           w={10}
  //           x={col.width||draggingState[key]}
  //           z={1}
  //           axis="x"
  //           draggable={true}
  //           resizable={false}
  //           onDragging={onDrag}
  //           onDragstop={onDragstop}
  //         />
  //       </th>
  //     );
  //   };
  //   this.components = {
  //     header: {
  //       cell: resizeableTitle,
  //     },
  //   };
  // },


  watch: {
    // pageHeight(val){
    //   // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
    //   if(!this.timer){
    //     // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
    //     this.pageHeight = val
    //     this.timer = true
    //     let that = this
    //     setTimeout(function(){
    //       // 打印screenWidth变化的值
    //       console.log(that.pageHeight)
    //       that.timer = false
    //     },100)
    //   }
    // }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  }
}
</script>

<style lang='less' scoped>
@import '~@assets/less/common.less';

/deep/ .ant-pagination {
  float: right;
}

///deep/ .resize-table-th {
//  position: relative;
//}
///deep/ .table-draggable-handle {
//  height: 100% !important;
//  bottom: 0;
//  left: auto !important;
//  right: -5px;
//  cursor: col-resize;
//  touch-action: none;
//}

</style>